//
//  KRLBannerView.m
//  KaraLive
//
//  Created by Zhijia Zhong on 2018/9/11.
//  Copyright © 2018年 naxigoren. All rights reserved.
//

#import "KRLBannerView.h"

//宏定义scrollview的宽高
#define KRL_BANNER_WIDTH self.frame.size.width
#define KRL_BANNER_HEIGHT self.frame.size.height

@interface KRLBannerView()<UIScrollViewDelegate>

@property(nonatomic, strong) UIScrollView * scrollView;
@property(nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation KRLBannerView {
    ///滚动的时间间隔
    NSTimeInterval _timeInterval;
    ///存放UIImage对象的数组
    NSArray *_imagesArray;
    ///存放3个UIImageView的数组
    NSMutableArray *_imageViews;
}

#pragma mark - 初始化轮播器控件

- (instancetype)initViewWithFrame:(CGRect)frame
                     timeInterval:(NSTimeInterval)timeInterval
                      imagesArray:(NSArray<UIImage *> *)imagesArray
                    clickCallBack:(KRLBannerClickCallBack)clickCallBack {
    if (self = [super initWithFrame:frame]) {
        self.bounds = frame;

        _timeInterval = timeInterval;
        self.clickBlcok = clickCallBack;
        _imagesArray = imagesArray;
        
        [self configSubviews];
        [self startTimer];
    }
    
    return self;
}

- (void)dealloc {
    [self stopTimer];
}

- (void)configSubviews {
    // 初始化scrollview
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    self.scrollView.contentSize = CGSizeMake(KRL_BANNER_WIDTH * 3, KRL_BANNER_HEIGHT);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    // 设置scrollview一开始的偏移量为一个宽度,因为里面有3个UIImageView,而我们显示的是中间的
    self.scrollView.contentOffset = CGPointMake(KRL_BANNER_WIDTH, 0);
    self.scrollView.delegate = self;
    [self addSubview:self.scrollView];
    
    //初始化imageview
    _imageViews = [NSMutableArray array];
    //创建三个imageView作为循环复用的载体，图片将循环加载在这三个imageView上面
    for (NSInteger i = 0; i < 3; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.frame = CGRectMake(KRL_BANNER_WIDTH * i, 0, KRL_BANNER_WIDTH, KRL_BANNER_HEIGHT);
        imageView.tag = (_imagesArray.count - 1 + i) % _imagesArray.count;
        imageView.userInteractionEnabled = YES;
        imageView.image = _imagesArray[imageView.tag];
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickImageView:)];
        [imageView addGestureRecognizer:tap];

        //将imageView加入数组中，方便随后取用
        [_imageViews addObject:imageView];
        [self.scrollView addSubview:imageView];
    }
    
    //初始化pageControl
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.scrollView.frame) - 30, KRL_BANNER_WIDTH, 30)];
    self.pageControl.numberOfPages = _imagesArray.count;
    self.pageControl.currentPage = 0;
    [self addSubview:self.pageControl];
}

// 图片轻敲手势事件
- (void)didClickImageView:(UITapGestureRecognizer *)tap {
    int index = (int)tap.view.tag;
    if (_clickBlcok) {
        _clickBlcok(index);
    }
}

//定时器调用的方法
- (void)nextPage {
    // 定时器方法都是相当于向左滑动, 即偏移量就要增大一个宽度
    // 执行了setContentOffset:方法, 系统会自动调用scrollViewDidEndScrollingAnimation:方法
    // 在这个方法里面再设置回偏移量等于一倍的宽度, 同时更换各个imageview的图片, 那么还是相当于中间的那个imageview显示在屏幕上
    [self.scrollView setContentOffset:CGPointMake(KRL_BANNER_WIDTH * 2, 0) animated:YES];
}

//停止定时器
- (void)stopTimer {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

//开启定时器
- (void)startTimer {
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    //加入NSRunLoopCommonModes运行模式,这样可以让定时器无论是在默认还是拖拽模式下都可以正常运作
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}


#pragma mark - <UIScrollViewDelegate代理方法>

//用户开始拖拽,停止定时器
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
    
}

//用户停止拖拽,开启定时器
- (void) scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
    
}

//人为拖拽停止并且减速完全停止时会调用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self updateImageViewsAndPageControl];
}

//在调用setContentOffset方法的时候，会触发此代理方法
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self updateImageViewsAndPageControl];
}


#pragma mark - 更新图片和分页控件的当前页
- (void)updateImageViewsAndPageControl {
    // 先判断出scrollview的操作行为是向左向右还是不动
    // 左滑+1，右滑-1
    int flag = 0;
    if (self.scrollView.contentOffset.x > KRL_BANNER_WIDTH) {
        flag = 1;
    } else if (self.scrollView.contentOffset.x == 0) {
        flag = -1;
    } else {
        return;
    }

    for (UIImageView *imageView in _imageViews) {
        NSInteger index = imageView.tag + flag ;
        
        if (index < 0) {
            index = self.pageControl.numberOfPages - 1;
        } else if (index >= self.pageControl.numberOfPages) {
            index = 0;
        }
        
        imageView.tag = index;
        imageView.image = _imagesArray[imageView.tag];
    }

    self.pageControl.currentPage = [_imageViews[1] tag];
    
    // 使用无动画的效果快速切换,也就是把scrollview的偏移量恢复成一个imageview的宽度
    self.scrollView.contentOffset = CGPointMake(KRL_BANNER_WIDTH, 0);
}

@end
